<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="支付方式" prop="paymentType">
        <el-select
          v-model="queryParams.paymentType"
          placeholder="请选择支付方式"
          clearable
        >
          <el-option
            v-for="dict in dict.type.oayment_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="订单状态" prop="status">
        <el-select
          v-model="queryParams.status"
          placeholder="请选择订单状态"
          clearable
        >
          <el-option
            v-for="dict in dict.type.order_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['order:order:add']"
          >新增</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['order:order:edit']"
          >修改</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['order:order:remove']"
          >删除</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['order:order:export']"
          >导出</el-button
        >
      </el-col>
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="orderList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="订单ID" align="center" prop="id" />
      <el-table-column label="订单编号" align="center" prop="orderNo" />
      <el-table-column label="用户ID" align="center" prop="userId" />
      <el-table-column label="订单总金额" align="center" prop="totalAmount" />
      <el-table-column label="实付金额" align="center" prop="paymentAmount" />
      <el-table-column label="运费" align="center" prop="freightAmount" />
      <el-table-column label="优惠金额" align="center" prop="discountAmount" />
      <el-table-column
        label="优惠券抵扣金额"
        align="center"
        prop="couponAmount"
      />
      <el-table-column label="支付方式" align="center" prop="paymentType">
        <template slot-scope="scope">
          <dict-tag
            :options="dict.type.oayment_type"
            :value="scope.row.paymentType"
          />
        </template>
      </el-table-column>
      <el-table-column label="订单状态" align="center" prop="status">
        <template slot-scope="scope">
          <dict-tag
            :options="dict.type.order_status"
            :value="scope.row.status"
          />
        </template>
      </el-table-column>
      <el-table-column
        label="支付时间"
        align="center"
        prop="paymentTime"
        width="180"
      >
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.paymentTime, "{y}-{m}-{d}") }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="发货时间"
        align="center"
        prop="deliveryTime"
        width="180"
      >
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.deliveryTime, "{y}-{m}-{d}") }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="收货时间"
        align="center"
        prop="receiveTime"
        width="180"
      >
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.receiveTime, "{y}-{m}-{d}") }}</span>
        </template>
      </el-table-column>
      <el-table-column label="收货人姓名" align="center" prop="receiverName" />
      <el-table-column label="收货人电话" align="center" prop="receiverPhone" />
      <el-table-column label="收货地址" align="center" prop="receiverAddress" />
      <el-table-column label="订单备注" align="center" prop="note" />
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['order:order:edit']"
            >修改</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['order:order:remove']"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改订单对话框 -->
    <el-dialog
      :title="title"
      :visible.sync="open"
      width="1000px"
      append-to-body
    >
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="订单编号" prop="orderNo">
          <el-input v-model="form.orderNo" placeholder="请输入订单编号" />
        </el-form-item>
        <el-form-item label="用户ID" prop="userId">
          <el-input v-model="form.userId" placeholder="请输入用户ID" />
        </el-form-item>
        <el-form-item label="订单总金额" prop="totalAmount">
          <el-input v-model="form.totalAmount" placeholder="请输入订单总金额" />
        </el-form-item>
        <el-form-item label="实付金额" prop="paymentAmount">
          <el-input v-model="form.paymentAmount" placeholder="请输入实付金额" />
        </el-form-item>
        <el-form-item label="运费" prop="freightAmount">
          <el-input v-model="form.freightAmount" placeholder="请输入运费" />
        </el-form-item>
        <el-form-item label="优惠金额" prop="discountAmount">
          <el-input
            v-model="form.discountAmount"
            placeholder="请输入优惠金额"
          />
        </el-form-item>
        <el-form-item label="优惠券抵扣金额" prop="couponAmount">
          <el-input
            v-model="form.couponAmount"
            placeholder="请输入优惠券抵扣金额"
          />
        </el-form-item>
        <el-form-item label="支付方式" prop="paymentType">
          <el-select v-model="form.paymentType" placeholder="请选择支付方式">
            <el-option
              v-for="dict in dict.type.oayment_type"
              :key="dict.value"
              :label="dict.label"
              :value="parseInt(dict.value)"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="订单状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio
              v-for="dict in dict.type.order_status"
              :key="dict.value"
              :label="parseInt(dict.value)"
              >{{ dict.label }}</el-radio
            >
          </el-radio-group>
        </el-form-item>
        <el-form-item label="支付时间" prop="paymentTime">
          <el-date-picker
            clearable
            v-model="form.paymentTime"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="请选择支付时间"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="发货时间" prop="deliveryTime">
          <el-date-picker
            clearable
            v-model="form.deliveryTime"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="请选择发货时间"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="收货时间" prop="receiveTime">
          <el-date-picker
            clearable
            v-model="form.receiveTime"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="请选择收货时间"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="收货人姓名" prop="receiverName">
          <el-input
            v-model="form.receiverName"
            placeholder="请输入收货人姓名"
          />
        </el-form-item>
        <el-form-item label="收货人电话" prop="receiverPhone">
          <el-input
            v-model="form.receiverPhone"
            placeholder="请输入收货人电话"
          />
        </el-form-item>
        <el-form-item label="收货地址" prop="receiverAddress">
          <el-input
            v-model="form.receiverAddress"
            placeholder="请输入收货地址"
          />
        </el-form-item>
        <el-form-item label="订单备注">
          <editor v-model="form.note" :min-height="192" />
        </el-form-item>
        <el-divider content-position="center">商品信息信息</el-divider>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button
              type="primary"
              icon="el-icon-plus"
              size="mini"
              @click="handleAddProducts"
              >添加</el-button
            >
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              @click="handleDeleteProducts"
              >删除</el-button
            >
          </el-col>
        </el-row>
        <el-table
          :data="productsList"
          :row-class-name="rowProductsIndex"
          @selection-change="handleProductsSelectionChange"
          ref="products"
        >
          <el-table-column type="selection" width="50" align="center" />
          <el-table-column
            label="序号"
            align="center"
            prop="index"
            width="50"
          />
          <el-table-column label="商品名称" prop="name" width="150">
            <template slot-scope="scope">
              <el-input v-model="scope.row.name" placeholder="请输入商品名称" />
            </template>
          </el-table-column>
          <el-table-column
            label="品牌ID(关联brand表)"
            prop="brandId"
            width="150"
          >
            <template slot-scope="scope">
              <el-input
                v-model="scope.row.brandId"
                placeholder="请输入品牌ID(关联brand表)"
              />
            </template>
          </el-table-column>
          <el-table-column label="商品类别" prop="category" width="150">
            <template slot-scope="scope">
              <el-input
                v-model="scope.row.category"
                placeholder="请输入商品类别"
              />
            </template>
          </el-table-column>
          <el-table-column label="商品价格" prop="price" width="150">
            <template slot-scope="scope">
              <el-input
                v-model="scope.row.price"
                placeholder="请输入商品价格"
              />
            </template>
          </el-table-column>
          <el-table-column label="库存数量" prop="stock" width="150">
            <template slot-scope="scope">
              <el-input
                v-model="scope.row.stock"
                placeholder="请输入库存数量"
              />
            </template>
          </el-table-column>
          <el-table-column label="记录创建时间" prop="createdAt" width="240">
            <template slot-scope="scope">
              <el-date-picker
                clearable
                v-model="scope.row.createdAt"
                type="date"
                value-format="yyyy-MM-dd"
                placeholder="请选择记录创建时间"
              />
            </template>
          </el-table-column>
          <el-table-column
            label="记录最后更新时间"
            prop="updatedAt"
            width="240"
          >
            <template slot-scope="scope">
              <el-date-picker
                clearable
                v-model="scope.row.updatedAt"
                type="date"
                value-format="yyyy-MM-dd"
                placeholder="请选择记录最后更新时间"
              />
            </template>
          </el-table-column>
        </el-table>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listOrder,
  getOrder,
  delOrder,
  addOrder,
  updateOrder,
} from "@/api/order/order";

export default {
  name: "Order",
  dicts: ["order_status", "oayment_type"],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 子表选中数据
      checkedProducts: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 订单表格数据
      orderList: [],
      // 商品信息表格数据
      productsList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        paymentType: null,
        status: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        orderNo: [
          { required: true, message: "订单编号不能为空", trigger: "blur" },
        ],
        userId: [
          { required: true, message: "用户ID不能为空", trigger: "blur" },
        ],
        totalAmount: [
          { required: true, message: "订单总金额不能为空", trigger: "blur" },
        ],
        paymentAmount: [
          { required: true, message: "实付金额不能为空", trigger: "blur" },
        ],
        freightAmount: [
          { required: true, message: "运费不能为空", trigger: "blur" },
        ],
        discountAmount: [
          { required: true, message: "优惠金额不能为空", trigger: "blur" },
        ],
        couponAmount: [
          {
            required: true,
            message: "优惠券抵扣金额不能为空",
            trigger: "blur",
          },
        ],
        paymentType: [
          { required: true, message: "支付方式不能为空", trigger: "change" },
        ],
        status: [
          { required: true, message: "订单状态不能为空", trigger: "change" },
        ],
        paymentTime: [
          { required: true, message: "支付时间不能为空", trigger: "blur" },
        ],
        deliveryTime: [
          { required: true, message: "发货时间不能为空", trigger: "blur" },
        ],
        receiveTime: [
          { required: true, message: "收货时间不能为空", trigger: "blur" },
        ],
        receiverName: [
          { required: true, message: "收货人姓名不能为空", trigger: "blur" },
        ],
        receiverPhone: [
          { required: true, message: "收货人电话不能为空", trigger: "blur" },
        ],
        receiverAddress: [
          { required: true, message: "收货地址不能为空", trigger: "blur" },
        ],
        note: [
          { required: true, message: "订单备注不能为空", trigger: "blur" },
        ],
        createTime: [
          { required: true, message: "创建时间不能为空", trigger: "blur" },
        ],
        updateTime: [
          { required: true, message: "更新时间不能为空", trigger: "blur" },
        ],
      },
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询订单列表 */
    getList() {
      this.loading = true;
      listOrder(this.queryParams).then((response) => {
        this.orderList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        orderNo: null,
        userId: null,
        totalAmount: null,
        paymentAmount: null,
        freightAmount: null,
        discountAmount: null,
        couponAmount: null,
        paymentType: null,
        status: null,
        paymentTime: null,
        deliveryTime: null,
        receiveTime: null,
        receiverName: null,
        receiverPhone: null,
        receiverAddress: null,
        note: null,
        createTime: null,
        updateTime: null,
      };
      this.productsList = [];
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加订单";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids;
      getOrder(id).then((response) => {
        this.form = response.data;
        this.productsList = response.data.productsList;
        this.open = true;
        this.title = "修改订单";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          this.form.productsList = this.productsList;
          if (this.form.id != null) {
            updateOrder(this.form).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addOrder(this.form).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal
        .confirm('是否确认删除订单编号为"' + ids + '"的数据项？')
        .then(function () {
          return delOrder(ids);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    /** 商品信息序号 */
    rowProductsIndex({ row, rowIndex }) {
      row.index = rowIndex + 1;
    },
    /** 商品信息添加按钮操作 */
    handleAddProducts() {
      let obj = {};
      obj.name = "";
      obj.brandId = "";
      obj.category = "";
      obj.price = "";
      obj.stock = "";
      obj.description = "";
      obj.createdAt = "";
      obj.updatedAt = "";
      this.productsList.push(obj);
    },
    /** 商品信息删除按钮操作 */
    handleDeleteProducts() {
      if (this.checkedProducts.length == 0) {
        this.$modal.msgError("请先选择要删除的商品信息数据");
      } else {
        const productsList = this.productsList;
        const checkedProducts = this.checkedProducts;
        this.productsList = productsList.filter(function (item) {
          return checkedProducts.indexOf(item.index) == -1;
        });
      }
    },
    /** 复选框选中数据 */
    handleProductsSelectionChange(selection) {
      this.checkedProducts = selection.map((item) => item.index);
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "order/order/export",
        {
          ...this.queryParams,
        },
        `order_${new Date().getTime()}.xlsx`
      );
    },
  },
};
</script>
